<template>
    <el-row>
        mean: {{ sat.mean }}
        median: {{ sat.median }}
    </el-row>
    <div class="block">
      <el-date-picker
        v-model="dateSelect"
        type="date"
        placeholder="Pick a day"
        :disabled-date="disabledDate"
        :shortcuts="shortcuts"
      />
      <el-button type="primary" round
      @click="getTradingRankDetail" >确定</el-button>
    </div>

    <el-table :data="state.data" 
    :cell-class-name="tableCellClassName"
    @sort-change="sortChange"
    @cell-click="industryClick"
    :default-sort="state.sort"
    @header-click="tableHeaderClick"
    style="width: 100%" height="800">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="category" label="类别" width="100" 
            :filter-method="filterCategory"
            :filters="[
                { text: '股票', value: '股票' },
                { text: 'ETF', value: 'ETF' },
                { text: '指数', value: '指数' },
            ]"
        />
        <el-table-column prop="stock" label="股票" width="150">
            <template #default="scope">
                <ToStockDetail :stock="scope.row.stock" />
            </template> 
        </el-table-column>
        <el-table-column prop="display" label="display" width="100" >    
            <template #default="scope">
                <ToDDisplay :stock="scope.row.stock" :date="scope.row.date" />
            </template>
        </el-table-column>
        <el-table-column prop="industry" label="industry" width="140"/>
        <el-table-column prop="lp" label="lp" sortable width="100"/>
        <el-table-column prop="close" label="价格" width="100"/>
        <el-table-column prop="drawdown" label="drawdown" width="100" sortable/>
        <el-table-column prop="pct" label="pct" width="80" sortable />
        <el-table-column prop="nextPct" label="nextPct" width="80" sortable />
        <el-table-column prop="pct3D" label="pct3D" width="80" sortable />
        <el-table-column prop="pct5D" label="pct5D" width="80" sortable />
        <el-table-column prop="gt20d" label="gt20d" sortable width="100"/>
        <el-table-column prop="gt30d" label="gt30d" sortable width="100"/>
        <el-table-column prop="gt60d" label="gt60d" sortable width="100"/>
    </el-table>
</template>

<script setup>
import { ref, reactive } from 'vue'

import { formatDate } from "@/utils/help"
import { getTradingRankDetailData } from '../../service/rank';
import { getIndexName, getLpClassName, getSessionStorage, setSessionStorage } from '../../utils/help';
import ToStockDetail from '@/components/ToStockDetail.vue';
import ToDDisplay from '../element/ToDDisplay.vue';
import { useRouteQuery } from '../../utils/useRoute';
import * as ss from 'simple-statistics';

const base = "TradingRankDetail"
const industrySelectKey = base + "Industry" + "Select"
const sortPropKey = base + "SortProp"
const sortOrderKey = base + "SortOrder"

const dateSelect = ref("")
const state = reactive({
    rawData: [],
    data : [],
    date : "",
    stocks: [],
    operationSelected: "",
    industryTags: new Set(),
    industrySelected: getSessionStorage(industrySelectKey) || "全部",
    sort: { 
        prop: sessionStorage.getItem(sortPropKey) || 'date' , 
        order: sessionStorage.getItem(sortOrderKey) || 'descending' 
    },
})

const sat = reactive({
    pcts: [],
    mean: 0,
    median: 0,
})

const shortcuts = [
    {
        text: 'Today',
        value: new Date(),
    },
    {
        text: 'Yesterday',
        value: () => {
        const date = new Date()
        date.setTime(date.getTime() - 3600 * 1000 * 24)
        return date
        },
    },
    {
        text: 'A week ago',
        value: () => {
        const date = new Date()
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
        return date
        },
    },]

const disabledDate = (time) => {
    return time.getTime() > Date.now()
}

let stocks = useRouteQuery("stocks", "")
if (stocks) {
    state.stocks = stocks.split(";")
}


const loadData = () => { 
    getTradingRankDetailData(state.date).then(res => {
        state.rawData = res.data
        state.data = res.data

        if (state.stocks.length > 0) {
            state.data = state.rawData.filter(item => state.stocks.includes(item.stock))
        }

        state.rawData.forEach(item => {
            sat.pcts.push(item.pct)
        })
        sat.mean = ss.mean(sat.pcts).toFixed(2)
        sat.median = ss.median(sat.pcts).toFixed(2)
    })
}

const getTradingRankDetail = () => {
    state.date = formatDate(dateSelect.value)
    loadData()
}

loadData()


const tableCellClassName = ({row, column, rowIndex, columnIndex}) => {
    var columnProperty = column.property
    if (["lp","lp5d","lp10d","lp15d","lp20d"].includes(columnProperty)) {
        return getLpClassName(row[columnProperty])
    }

    if (['pct','pct3D','pct5D','nextPct'].includes(columnProperty)) {
        if (row[columnProperty] < 0) {
            return 'pctlt0-cell'
        } else {
            return ''
        }
    }

    if (["closeRank", "moneyRank", "volumeRank", "pbRank","pct3DRank","pct5DRank"].includes(columnProperty)) {
        if (row[columnProperty] >= 700) {
            return 'rank-gt700-cell'
        } 

        if (row[columnProperty] <= 50) {
            return 'rank-lt50-cell'
        } 
    }

    if (["gt60d","gt5d", "gt30d","gt20d","lowGt20d","lowGt30d"].includes(columnProperty)) {
        if (row[columnProperty] >= 0) {
            return 'd300up-cell'
        } else {
            return 'd300down-cell'
        }
    }

    if (getIndexName().includes(row.stock)) {
        return 'lp-warning-row'
    }
}

const industryClick = (row, column, cell, event) => {
    let columnProperty = column.property
    let val = row[columnProperty]

    if (['industry'].includes(columnProperty)) {
        if (state.operationSelected != "" && state.operationSelected == val) {
            state.operationSelected = ""
            state.data = state.rawData
        } else {
            state.operationSelected = val
            if (["curPct","cur60wPct","nextWeekPct"].includes(columnProperty)) {
                if (val >= 0) {
                    state.data = state.rawData.filter(item => item[columnProperty] >= 0)
                } else {
                    state.data = state.rawData.filter(item => item[columnProperty] < 0)
                }
            } else {
                state.data = state.rawData.filter(item => item[columnProperty] == val)
            }
        }
    }
}

const filterCategory = (value, row) => {
    return row.category === value
}
</script>